package com.haitaoit.chengquan.module.center_service.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.activity.info.update.UpdateNameActivity;
import com.haitaoit.chengquan.module.center.activity.info.update.UpdatePhoneActivity;
import com.haitaoit.chengquan.module.center.activity.info.update.UpdatePwdActivity;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.module.center_service.activity.xuqiu_order.FaceBackActivity;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.haitaoit.chengquan.view.CircleImageView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ServiceInfoActivity extends BaseActivity {
    @ViewInject(R.id.center_img)
    CircleImageView center_img;
    @ViewInject(R.id.line_1)
    View line_1;
    @ViewInject(R.id.service_gsnametv)
    TextView service_gsnametv;
    @ViewInject(R.id.service_gsname)
    TextView service_gsname;
    @ViewInject(R.id.service_gsjstv)
    TextView service_gsjstv;
    @ViewInject(R.id.service_imgtv)
    TextView service_imgtv;
    @ViewInject(R.id.service_zzjsLL)
    LinearLayout service_zzjsLL;
    @ViewInject(R.id.service_lxrLL)
    LinearLayout service_lxrLL;
    @ViewInject(R.id.face_back)
    LinearLayout face_back;
    @ViewInject(R.id.service_lxr)
    TextView service_lxr;
    @ViewInject(R.id.service_address)
    TextView service_address;
    @ViewInject(R.id.service_scope)
    TextView service_scope;
    @ViewInject(R.id.company_introduction)
    TextView company_introduction;
    @ViewInject(R.id.service_phone)
    TextView service_phone;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_service_info);
        setLeftShow(1, R.mipmap.left);
        setTitle_V("我的资料");
        backLeft_V();
        ViewUtils.inject(this);


        // 个人服务商  企业服务商
        if (PreferenceUtils.getPrefString("account_type", "").equals("2")) {
            service_imgtv.setText("我的头像");
            service_gsnametv.setText("姓名");
            service_gsjstv.setText("个人介绍");
            service_zzjsLL.setVisibility(View.VISIBLE);
            service_lxrLL.setVisibility(View.GONE);
            line_1.setVisibility(View.GONE);

            httpGetUserInfo(Constant.Getgr_user_model);
        } else if (PreferenceUtils.getPrefString("account_type", "").equals("3")) {
            service_imgtv.setText("公司logo");
            service_gsnametv.setText("公司名称");
            service_gsjstv.setText("公司介绍");
            service_zzjsLL.setVisibility(View.VISIBLE);
            service_lxrLL.setVisibility(View.VISIBLE);

            httpGetUserInfo(Constant.Getqy_user_model);
        }
    }

    @OnClick({R.id.right, R.id.service_imgll, R.id.service_gsnamell, R.id.service_lxrLL,
            R.id.service_addressLL, R.id.service_fwfwLL, R.id.service_gsjsLL, R.id.service_zzjsLL,
            R.id.service_phoneLL, R.id.service_updatepwd, R.id.user_exit,R.id.face_back})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.right:
                break;
            case R.id.service_imgll:
                Dialog dlg = DialogUtil.ShowPhotoDialog(ServiceInfoActivity.this, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.tv_photos:// 图库
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 500);
                                intent.putExtra("outputY", 500);
                                intent.putExtra("crop", "true");
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 2);
                                break;
                            case R.id.tv_camera:
                                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(in, 2);
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();

                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 屏幕宽度（像素）
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.width = width;
                params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.service_gsnamell:// 公司名称
                intent.setClass(ServiceInfoActivity.this, UpdateNameActivity.class);
                intent.putExtra("SERVICE_GSNAMELL_TITLE", service_gsname.getText().toString().trim());
                startActivityForResult(intent, 5);
                break;
            case R.id.service_lxrLL:// 联系人
                intent.setClass(ServiceInfoActivity.this, UpdateNameActivity.class);
                intent.putExtra("SERVICE_LXRLL_TITLE", service_lxr.getText().toString().trim());

                startActivityForResult(intent, 7);
                break;
            case R.id.service_addressLL:// 地址
                intent.setClass(ServiceInfoActivity.this, UpdateNameActivity.class);
                intent.putExtra("SERVICE_ADDRESSLL_TITLE", service_address.getText().toString().trim());
                startActivityForResult(intent, 6);
                break;
            case R.id.service_fwfwLL:// 服务范围
                intent.setClass(ServiceInfoActivity.this, ServiceFanweiActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("fwfw", UserInfoModel.getUser_info().getService_scope());
                startActivityForResult(intent, 4);
                break;
            case R.id.service_gsjsLL:// 公司介绍
                intent.setClass(ServiceInfoActivity.this, ServiceFanweiActivity.class);
                // 个人服务商  企业服务商
                if (PreferenceUtils.getPrefString("account_type", "").equals("2")) {
                    intent.putExtra("type", "2");
                    intent.putExtra("fwfw", UserInfoModel.getUser_info().getCompany_introduction());
                } else if (PreferenceUtils.getPrefString("account_type", "").equals("3")) {
                    intent.putExtra("type", "3");
                    intent.putExtra("fwfw", UserInfoModel.getUser_info().getCompany_introduction());
                }
                startActivityForResult(intent, 4);
                break;
            case R.id.service_zzjsLL:// 资质介绍
                intent.setClass(ServiceInfoActivity.this, QualificationActivity.class);
                startActivity(intent);
                break;
            case R.id.service_phoneLL:// 手机
                intent.setClass(ServiceInfoActivity.this, UpdatePhoneActivity.class);
                startActivity(intent);
                break;
            case R.id.service_updatepwd:// 修改密码
                intent.setClass(ServiceInfoActivity.this, UpdatePwdActivity.class);
                intent.putExtra("type", "service");
                startActivity(intent);
                break;
            case R.id.user_exit:// 退出
                PreferenceUtils.setPrefString("user_id", "");
                PreferenceUtils.setPrefString("account_type", "");
                PreferenceUtils.setPrefString("password", "");
                intent.setClass(ServiceInfoActivity.this, LoginActivity.class);
                intent.putExtra("tag", "2");
                startActivity(intent);
                finish();
                break;
            //意见反馈
            case R.id.face_back:

                intent.setClass(ServiceInfoActivity.this, FaceBackActivity.class);
                startActivity(intent);
                break;
        }
        super.onClick(v);
    }


    private void httpGetUserInfo(String url) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            UserInfoModel.setUser_info(user_info);

                            ImageLoader.getInstance().displayImage(user_info.getHead_portrait(), center_img);
                            service_gsname.setText(user_info.getReal_name());
                            service_lxr.setText(user_info.getContact());
                            service_address.setText(user_info.getAddress());
                            if (user_info.getService_scope().length() > 5) {
                                service_scope.setText(user_info.getService_scope().substring(0, 5));
                            } else {
                                service_scope.setText(user_info.getService_scope());
                            }
                            if (user_info.getCompany_introduction().length() > 5) {
                                company_introduction.setText(user_info.getCompany_introduction().substring(0, 5));
                            } else {
                                company_introduction.setText(user_info.getCompany_introduction());
                            }
                            service_phone.setText(user_info.getPhone());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 修改头像
    private void httpGetUpdateHead(String file, final Bitmap upbitmap) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.update_head_portrait
                + "user_id=" + PreferenceUtils.getPrefString("user_id", "") + "&sign=" + sign;

        JSONObject json = new JSONObject();
        try {
            json.put("head_portrait", file);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, false, url, json, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            center_img.setImageBitmap(upbitmap);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 记录文件名
    private String filename;
    // 上传的bitmap
    private Bitmap upbitmap;
    private String file = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 4:
                if (resultCode == 1) {// 服务范围
                    if (data.getStringExtra("Fanwei").length() > 5) {
                        service_scope.setText(data.getStringExtra("Fanwei").substring(0, 5));
                    } else {
                        service_scope.setText(data.getStringExtra("Fanwei"));
                    }
                    UserInfoModel.getUser_info().setService_scope(data.getStringExtra("Fanwei"));
                } else if (resultCode == 2) {// 介绍
                    if (data.getStringExtra("Fanwei").length() > 5) {
                        company_introduction.setText(data.getStringExtra("Fanwei").substring(0, 5));
                    } else {
                        company_introduction.setText(data.getStringExtra("Fanwei"));
                    }
                    UserInfoModel.getUser_info().setCompany_introduction(data.getStringExtra("Fanwei"));
                }
                break;
            case 1: // 解成bitmap,方便裁剪
                Bitmap bitmap = BitmapFactory.decodeFile(Environment
                        .getExternalStorageDirectory().getPath() + "/" + filename);
                float wight = bitmap.getWidth();
                float height = bitmap.getHeight();
                ZoomBitmap.zoomImage(bitmap, wight / 8, height / 8);
                upbitmap = ZoomBitmap.zoomImage(bitmap, wight / 19, height / 19);
                center_img.setImageBitmap(upbitmap);
                break;
            case 2:
                if (data != null) {
                    upbitmap = null;
                    if (data.getExtras() != null && !("").equals(data.getExtras())) {
                        upbitmap = (Bitmap) data.getExtras().get("data");
                    } else {
                        String str = data.getDataString();
                        if (str == null) {
                            return;
                        }
                        Uri uri = Uri.parse(str);
                        String path = GetAbserlutePath.getPath(this, uri);
                        if (path.endsWith("png") || path.endsWith("jpg")) {// 图片
                            upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                        } else {
                            ToastUtils.showToast("请选择.jpg或.png格式的图片！");
                            return;
                        }
                    }
                    upbitmap = getSmallBitmap(upbitmap);
                    file = bitmapToString(upbitmap);
//                    center_img.setImageBitmap(upbitmap);
                    httpGetUpdateHead(file, upbitmap);
                }
                break;
            case 5:
                if (resultCode == 101){
                    service_gsname.setText(data.getStringExtra("COMPANY_NAME"));
                }

                break;
            case 6:
                if (resultCode == 103){
                    service_address.setText(data.getStringExtra("ADDRESS_NAME"));
                }
                break;
            case 7:
                if (resultCode == 102){
                    service_lxr.setText(data.getStringExtra("LIANXI_NAME"));
                }else {
                    ToastUtils.showToast("审核通过后才可以修改名称");
                }
                break;
        }
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

}
